import {defineStore} from "pinia";
import {reqLogin, reqUserInfo, reqLogout} from "@/api/user";
import type {loginDataInter, loginResponseInter, userInfoResponseInter, logoutInter} from "@/api/user/type.ts";
import type {userStateInter} from "@/store/modules/types/type.ts";
import {SET_TOKEN, GET_TOKEN, REMOVE_TOKEN} from "@/utils/token.ts";
import {constantRoutes, asyncRoutes, anyRoutes} from "@/router/routes.ts";
import {filterAsyncRoutes} from "@/utils/filterRoutes.ts";
import router from "@/router";
import {cloneDeep} from "lodash";

let useUserStore = defineStore('user', {
    state: (): userStateInter => {
        return {
            token: GET_TOKEN() || undefined,
            menuRoutes: constantRoutes, // 仓库路由
            asyncRoutesList: [], // 异步路由
            userInfo: {
                username: '',
                avatar: ''
            },
            roleButtons: []
        }
    },
    actions: {
        // 用户登录接口
        async userLoginStore(data: loginDataInter) {
            let res: loginResponseInter = await reqLogin(data)
            if (res.code === 200) {
                this.token = res.data
                if (res.data) {
                    SET_TOKEN(res.data)
                }
                return 'ok'
            } else {
                return Promise.reject(res.message)
            }
        },
        // 获取用户信息
        async userInfoStore() {
            let res: userInfoResponseInter = await reqUserInfo()
            if (res.code === 200) {
                this.userInfo.username = res.data.name
                this.userInfo.avatar = res.data.avatar
                this.roleButtons = res.data.buttons
                this.clearAsyncRoutes()
                // 过滤路由
                let asyncRoutesMenus = filterAsyncRoutes(cloneDeep(asyncRoutes), res.data.routes)
                this.menuRoutes = [...constantRoutes, ...asyncRoutesMenus, ...anyRoutes]
                this.asyncRoutesList = [...asyncRoutesMenus, ...anyRoutes]
                this.asyncRoutesList.forEach((item: any) => {
                    router.addRoute(item)
                })
                return 'ok'
            } else {
                return Promise.reject(res.message)
            }
        },
        clearAsyncRoutes() {
            this.asyncRoutesList.forEach((item: any) => {
                router.removeRoute(item.name)
            })
            this.asyncRoutesList = []
        },
        // 退出登录
        async userLogout() {
            let res: logoutInter = await reqLogout()
            if (res.code === 200) {
                this.userInfo = {
                    username: '',
                    avatar: ''
                }
                this.token = ''
                REMOVE_TOKEN()
                this.clearAsyncRoutes()
                return 'ok'
            } else {
                return Promise.reject(res.message)
            }

        }
    },
    getters: {}
})
export default useUserStore
